import { Folder } from '@/types/global';
import { formatDate } from '@/utils/utils';
import { useCloned } from '@vueuse/core';
import { computed, nextTick, ref } from 'vue';
import { nanoid } from 'nanoid';
// eslint-disable-next-line import/no-cycle
import { deleteById } from '@/store/program/utils';
import { message } from './components/message/bus';
import { notify } from './components/notify/bus';

const folderObject: Folder = {
  title: '',
  editMode: false,
  id: '',
  type: '',
  date: formatDate(new Date()),
  sort: -1,
  children: [],
};
export const currentFolder = ref<Folder>({
  ...folderObject,
});
export const resetCurrentFolder = () => {
  currentFolder.value = {
    ...folderObject,
  };
};
export const activeId = ref<string>('');
/* 键盘指向 */
type TargetKey = 'folderKey' | 'fileKey' | undefined;
export const targetKey = ref<TargetKey>();

/* 中间区域的数据列表 */
export const cloneList = computed(() => {
  const result = useCloned(currentFolder.value.children || [])
    .cloned.value.sort((a, b) => {
      return b.type.length - a.type.length;
    })
    .sort((a, b) => {
      return b.sort - a.sort;
    });
  return result;
});
export const getWebIcon = (link: string) => {
  return `https://api.qqsuu.cn/api/dm-get?url=${link}`;
};

/*  */
export const selectList = ref<Folder[]>();
/* 创建文件夹 */
export const createFolder = () => {
  const data = selectList.value;
  if (!data || !currentFolder.value.children) {
    message('你需要选择一个目录再创建文件夹');
    return;
  }
  /* 当没有选择目录时，在根目录创建 */
  const folder: Folder = {
    title: '',
    editMode: true,
    id: nanoid(),
    type: 'folder',
    date: formatDate(new Date()),
    children: [],
    sort: currentFolder.value.children?.length || 0 + 100000,
  };
  if (!activeId.value) {
    data.push(folder);
  } else {
    folderObject.sort = currentFolder.value.children?.length || -1;
    currentFolder.value.showChildren = true;
    currentFolder.value.children?.push({ ...folder });
  }
  currentFolder.value = folder;
  activeId.value = folder.id;
};
export const deleteFolder = (id: string) => {
  notify({
    msg: '将会删除这个文件夹',
    title: '警告',
    onComfirm() {
      deleteById(id);
    },
  });
};
export const flexWidth = ref(320);
export const dragging = ref(false);
export const showSidebar = ref(true);
